package com.dylan.历史.多线程.并发编程的艺术.原子操作;

import com.dylan.历史.util.LogUtil;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * Created by Dylan on 2018/9/20.
 */
public class 更新字段 {

    // 创建原子更新器，并设置需要更新的对象类和对象的属性
    private static AtomicIntegerFieldUpdater<User> a =
            AtomicIntegerFieldUpdater.newUpdater(User.class, "age");

    public static void main(String[] args) {
        User user = new User("dylan", 29);
        a.getAndIncrement(user);
        LogUtil.info(user);
    }

    static class User {
        private String name;
        // 必须定义为 public volatile
        public volatile int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
